import { defineStore } from "pinia";
import { ref } from "vue";
import { ElMessage } from "element-plus";

// 封装对象
// const baseURL = "ws://192.168.3.212:7777";
const baseURL = "ws://192.168.3.210:8001";
class WsControl {
  constructor(path) {
    this.path = path;
    this.ws = new WebSocket(baseURL + path);
    this.ws.onopen = () => {
      console.log("链接成功")
      ElMessage.success("链接成功");
      isLink.value = true;
      reconnectNum.value = 1;
    }
    this.ws.onmessage = function (data) {
      if (data.data != "OK" && JSON.parse(data.data).msg == undefined) {
        const robotMsg = JSON.parse(data.data);
        if (!!callObj.value) {
          if (robotMsg.data?.option !== null && robotMsg.data?.option !== undefined) {
            // 智能检索页面数据需要处理
            setRobotData(robotMsg);
          } else {
            callObj.value.callBack(robotMsg, "success");
          }
        }
      }
    }
    this.ws.onclose = () => {
      console.log("链接关闭")
      isLink.value = false;
      // 如果是服务器断了，尝试重连
      clearTimeout(timer.value);
      timer.value = null;
      timer.value = setTimeout(() => {
        if (reconnectNum.value < 10) {
          reconnectNum.value++;
          chartStor().initChat(apiPath.value);
        } else {
          reconnectNum.value = 1;
          ElMessage.error("链接超时");
          console.log(callObj.value)
          if (!!callObj.value) {
            callObj.value.callBack(null, "error");
          }
        }
      }, 1000);
    }
    this.ws.onerror = () => {
      console.log("链接失败")
      isLink.value = false;
    }
  };
  path: "";
  ws: any;
  reconnectNum: number;
}
let apiPath = ref<string>("");
let wsObj = ref<any>(null);
let callObj = ref<any>(undefined);
let reconnectNum = ref<number>(1);
let isLink = ref<boolean>(false);
let timer = ref<any>(null);

function setRobotData(robotMsg) {
  if (robotMsg.data?.option?.type == "table") {
    // 类型为表格
    robotMsg.data.option.columns = [];
    robotMsg.data.option.datas = [];
    Object.keys(robotMsg.data.option.data).forEach((key, keyIndex) => {
      robotMsg.data.option.columns.push({ name: key });
      robotMsg.data.option.data[key].forEach((tr, trIndex) => {
        if (keyIndex == 0) {
          robotMsg.data.option.datas.push({
            [key]: tr,
          });
        } else {
          robotMsg.data.option.datas[trIndex][key] = tr;
        }
      });
    });
    robotMsg.data.option.data = Object.assign([], robotMsg.data.option.datas);
    delete robotMsg.data.option.datas;
    callObj.value.callBack(robotMsg, "success");
  } else if (robotMsg.data?.option?.type == "plot" && (robotMsg.data?.option?.data.plot_type == "bar" || robotMsg.data?.option?.data.plot_type == "line" || robotMsg.data?.option?.data.plot_type == "scatter")) {
    // 柱状图/折线图
    const params = {
      sessionId: robotMsg.sessionId,
      type: robotMsg.type,
      data: robotMsg.data
    }
    params.data.option = params.data.option.data;
    params.data.option.type = params.data.option.plot_type;
    delete params.data.option.data;
    delete params.data.option.plot_type;
    if (params.data.option.type == "scatter") {
      // 散点图特殊处理
      params.data.option.point = [];
      params.data.option.ys.forEach((item, index) => {
        params.data.option.point.push([params.data.option.xs[index], item]);
      })
      params.data.option.ys = params.data.option.point;
      delete params.data.option.point;
      delete params.data.option.xs;
    }
    console.log("折线图", params);
    callObj.value.callBack(params, "success");
  } else if (robotMsg.data?.option?.type == "plot" && robotMsg.data?.option?.data.plot_type == "pie") {
    // 饼图
    const params = {
      sessionId: robotMsg.sessionId,
      type: robotMsg.type,
      data: robotMsg.data
    }
    params.data.option = params.data.option.data;
    params.data.option.type = params.data.option.plot_type;
    params.data.option.xss = [];
    params.data.option.xs.forEach((item, index) => {
      params.data.option.xss.push({
        value: params.data.option.ys[index].toFixed(2) - 0,
        percentage: undefined,
        name: item,
        nm: "(个)",
      })
    });
    params.data.option.xs = params.data.option.xss;
    delete params.data.option.xss;
    delete params.data.option.data;
    delete params.data.option.plot_type;
    callObj.value.callBack(params, "success");
  } else if (robotMsg.data?.option?.type == "plot" && robotMsg.data?.option?.data.plot_type == "heatmap") {
    // 热力图
    const params = {
      sessionId: robotMsg.sessionId,
      type: robotMsg.type,
      data: robotMsg.data
    }
    params.data.option = params.data.option.data;
    params.data.option.type = params.data.option.plot_type;
    // 热力图数据结构需要处理下
    params.data.option.ys = [];
    params.data.option.zs.forEach((y, yIndex) => {
      y.forEach((x, xIndex) => {
        params.data.option.ys.push([xIndex, yIndex, x]);
      });
    });
    delete params.data.option.data;
    delete params.data.option.plot_type;
    delete params.data.option.zs;
    callObj.value.callBack(params, "success");
  }
}

// 文字问答
export const chartStor = defineStore(
  "chartStor",
  () => {
    const initChat = (path) => {
      apiPath.value = path;
      wsObj.value = new WsControl(path);
    }
    const setChat = (params) => {
      return new Promise(async (resolve, reject) => {
        callObj.value = params;
        wsObj.value.ws.send(JSON.stringify({
          type: "ask",
          sessionId: params.sessionId,
          data: {
            questionId: params.questionId,
            question: params.userMessageText,
            timestamp: new Date().getTime()
          }
        }));
      });
    }
    // 关闭链接
    const closeChat = () => {
      clearTimeout(timer.value);
      timer.value = null;
      reconnectNum.value = 1;
      wsObj.value.ws.close();
    }
    return { setChat, closeChat, initChat }
  },
  {
    // persist: {
    //   key: "sliderLogoStorage", //存储名称
    //   storage: localStorage, // 存储方式
    //   paths: ["logoText", "logoImg"], //指定 state 中哪些数据需要被持久化。[] 表示不持久化任何状态，undefined 或 null 表示持久化整个 state
    // },
  }
)